package net.hhk.twitter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import net.hhk.connect.HTTPConnect;
import net.hhk.data.Constant;
import net.hhk.data.MySharePreferences;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity implements OnClickListener  {
	static MySharePreferences sharePre;
    EditText userName;
    EditText pass;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        Button registerScreen = (Button) findViewById(R.id.btn_signUp);
        Button btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(this);
        userName = (EditText)findViewById(R.id.user_name);
        pass = (EditText) findViewById(R.id.pass);
        sharePre =(MySharePreferences) getApplicationContext();
        
        		
        // Listening to register new account link
        registerScreen.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// Switching to Register screen
				Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
				startActivity(i);
			}
		});
    }
    public void onClick(View v){
    	switch (v.getId()) {
		case R.id.btnLogin:
			String name = userName.getText().toString();
			String pas = pass.getText().toString();
			List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("username", name));
			postParameters.add(new BasicNameValuePair("password", pas));
//			postParameters.add(new BasicNameValuePair("username", "suko"));
//			postParameters.add(new BasicNameValuePair("password", "123456"));
			HTTPConnect connect = HTTPConnect.getConnect();
			
			String result = connect.doConnect(Constant.LOGIN, postParameters);
			result = result.trim();
			//result.trim();
			int id = Integer.parseInt(result);
//			int id = 1;
			if(id > 0){
				sharePre.setExitInt("myid", id);
				sharePre.setExitString("myUsername", name);
				sharePre.setExitString("currentVisitUsername", name);
				Intent i = new Intent(getApplicationContext(), MainActivity.class);
				Bundle b = new Bundle();
				b.putInt("id", id); //Your id
				i.putExtras(b); //Put your id to your next Inten
				startActivity(i);
			}
			else {
				TextView text = (TextView)findViewById(R.id.link_to_register);
				text.setText("invalid name or password");
				pass.setText("");
			}
			
			
			break;

		default:
			break;
		}
    }
}